package com.java.TCP.receive_feedback;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {
    static class ThreadSon extends Thread {
        private Socket socket;
        
        public ThreadSon(Socket socket) {
            this.socket = socket;
        }
        
        @Override
        public void run() {
            try {
                Scanner sendScanner = new Scanner(System.in);
                Scanner receiveScanner = new Scanner(socket.getInputStream());
                PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
                
                while (true) {
                    // 服务端接收数据
                    String receive = receiveScanner.nextLine();
                    System.out.println("客户端" + socket.getPort() + "对服务器说 " + receive);
                    
                    if ("再见".equals(receive)) {
                        break;
                    }
                    
                    // 服务端反馈数据
                    System.out.println("服务器对客户端" + socket.getPort() + "说 ");
                    String send = sendScanner.nextLine();
                    printWriter.println(send);
                    printWriter.flush();
                    
                    if ("再见".equals(send)) {
                        break;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        
        while (true) {
            Socket socket = serverSocket.accept();
            new ThreadSon(socket).start();
        }
    }
}
